<template>
  <div class="picture-list">
    <!-- 图片列表 -->
    <a-list
      :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }"
      :data-source="dataList"
      :loading="loading"
    >
      <template #renderItem="{ item: picture, index }">
        <a-list-item style="padding: 0">
          <!-- 单张图片 -->
          <a-card hoverable @click="doClickPicture(picture)">
            <template #cover>
              <img
                :alt="picture.name"
                :src="picture.thumbnailUrl ?? picture.url"
                style="height: 180px; object-fit: cover"
              />
            </template>
            <a-card-meta :title="picture.name">
              <template #description>
                <a-flex>
                  <a-tag color="green">
                    {{ picture.category ?? '默认' }}
                  </a-tag>
                  <a-tag v-for="tag in picture.tags" :key="tag">
                    {{ tag }}
                  </a-tag>
                </a-flex>
                <!-- 统计信息区域 -->
                <a-flex justify="space-between" align="center" style="padding: 0 8px">
                  <div class="stats-item">
                    <EyeOutlined style="color: #8c8c8c" />
                    <span style="margin-left: 4px; color: #8c8c8c">{{ Number(picture.viewCount) || 0 }}</span>
                  </div>
                  <div
                    class="stats-item like-btn"
                    :class="{ 'liked': isLikedMap.get(picture.id) }"
                    @click.stop="handleLike(picture)"
                  >
                    <HeartOutlined :style="{ color: isLikedMap.get(picture.id) ? '#eb2f96' : '#8c8c8c' }" />
                    <span style="margin-left: 4px; color: #8c8c8c">{{ Number(picture.likeCount) || 0 }}</span>
                  </div>
                </a-flex>
              </template>
            </a-card-meta>
            <template v-if="showOp" #actions>
              <ShareAltOutlined @click="(e) => doShare(picture, e)" />
              <SearchOutlined @click="(e) => doSearch(picture, e)" />
              <EditOutlined v-if="canEdit" @click="(e) => doEdit(picture, e)" />
              <DeleteOutlined v-if="canDelete" @click="(e) => doDelete(picture, e)" />
              <!-- 多选框 -->
              <a-checkbox
                v-if="canEdit"
                v-model="selectedArray[index]"
                @click="(e:any) => doChosed(index, picture,e)"
              ></a-checkbox>
            </template>
          </a-card>
        </a-list-item>
      </template>
    </a-list>
    <ShareModal ref="shareModalRef" :link="shareLink" />
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import {
  DeleteOutlined,
  EditOutlined,
  SearchOutlined,
  ShareAltOutlined,
  EyeOutlined,
  HeartOutlined
} from '@ant-design/icons-vue'
import { deletePictureUsingPost, incrementViewUsingPost, toggleLikeUsingPost } from '@/api/pictureController.ts'
import { message } from 'ant-design-vue'
import ShareModal from '@/components/ShareModal.vue'
import { ref, watch } from 'vue'

interface Props {
  dataList?: API.PictureVO[]
  loading?: boolean
  showOp?: boolean
  userId?: number // 当前用户ID
  canEdit?: boolean
  canDelete?: boolean
  onReload?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  dataList: () => [],
  loading: false,
  showOp: false,
  canEdit: false,
  canDelete: false
})

const router = useRouter()

const emit = defineEmits(['update:selectedPictures','like-changed'])

// 点赞状态管理
const isLikedMap = ref(new Map<number, boolean>())

// 初始化点赞状态（假设pictureVO中包含isLiked字段）
watch(() => props.dataList, (newList) => {
  newList.forEach(pic => {
    isLikedMap.value.set(pic.id, pic.isLiked || false)
  })
}, { immediate: true })

// 处理点赞操作
// PictureList.vue 修改点赞处理逻辑
const handleLike = async (picture: API.PictureVO) => {
  if (!props.userId) {
    message.warning('请先登录')
    return
  }

  try {
    // 先更新本地状态
    const newLiked = !isLikedMap.value.get(picture.id)
    const currentLikeCount = Number(picture.likeCount) || 0 // 强制转换为数字

    // 立即更新UI
    isLikedMap.value.set(picture.id, newLiked)
    picture.likeCount = newLiked ? currentLikeCount + 1 : Math.max(0, currentLikeCount - 1)

    // 发送异步请求
    const res = await toggleLikeUsingPost({
      pictureId: picture.id
    })

    if (res.data.code !== 0) {
      // 请求失败时回滚状态
      isLikedMap.value.set(picture.id, !newLiked)
      picture.likeCount = currentLikeCount
      message.error('操作失败')
    } else {
      emit('like-changed', picture.id, picture.likeCount)
    }
  } catch (e) {
    message.error('网络错误')
  }
}

// 多选框选中逻辑
// 布尔数组，用于记录每个图片的选中状态
const selectedArray = ref<boolean[]>([])

// 记录所有被选中的图片的索引
const selectedPictures = ref<number[]>([])



// 初始化布尔数组
watch(
  () => props.dataList,
  (newDataList) => {
    selectedArray.value = newDataList.map(() => false)
  },
  { immediate: true }
)

// 将更新后的 selectedPictures 发送给父组件
emit('update:selectedPictures', selectedPictures.value)


// 跳转至图片详情页
const doClickPicture = (picture: API.PictureVO) => {
  router.push({
    path: `/picture/${picture.id}`
  })
}

// 搜索
const doSearch = (picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  // 打开新的页面
  window.open(`/search_picture?pictureId=${picture.id}`)
}

// 选择
const doChosed = (index, picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  selectedArray.value[index] = !selectedArray.value[index]
  // console.log("这次选中：",selectedArray.value[index])
  if (selectedArray.value[index]) {
    // 如果当前被选中，添加到选中数组
    selectedPictures.value.push(picture.id)
    // console.log("这次添加到选中数组的是：",selectedArray.value[index])
  } else {
    // 如果当前被取消选中，从选中数组中移除
    selectedPictures.value = selectedPictures.value.filter((id) => id !== picture.id)
  }
  // console.log("当前选中的图片索引：", selectedPictures.value);
}

// 编辑
const doEdit = (picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  // 跳转时一定要携带 spaceId
  router.push({
    path: '/add_picture',
    query: {
      id: picture.id,
      spaceId: picture.spaceId
    }
  })
}

// 删除数据
const doDelete = async (picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  const id = picture.id
  if (!id) {
    return
  }
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    props.onReload?.()
  } else {
    message.error('删除失败')
  }
}

// ----- 分享操作 ----
const shareModalRef = ref()
// 分享链接
const shareLink = ref<string>()
// 分享
const doShare = (picture, e) => {
  // 阻止冒泡
  e.stopPropagation()
  shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.id}`
  if (shareModalRef.value) {
    shareModalRef.value.openModal()
  }
}

</script>

<style scoped>
.stats-item {
  display: flex;
  align-items: center;
  padding: 4px 8px;
  transition: all 0.3s;
}

.like-btn {
  cursor: pointer;
  border-radius: 4px;
}

.like-btn:hover {
  background-color: #fff1f0;
}

.like-btn:hover :deep(svg) {
  color: #eb2f96 !important;
}

.liked {
  color: #eb2f96;
}
</style>
